import 'package:flutter/cupertino.dart';
/**
 * 手机登录
 * page手机登录
 */
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:qgchat/common/action/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/user.dart';
import 'package:url_launcher/url_launcher.dart';

class PhoneLogin extends StatefulWidget {
  PhoneLogin({Key key}) : super(key: key);

  @override
  _PhoneLoginState createState() => _PhoneLoginState();
}

class _PhoneLoginState extends State<PhoneLogin>
    with SingleTickerProviderStateMixin {
  // 是否可登录(输入条件都满足)
  bool canLogin = true;
  // 手机输入框控制器
  TextEditingController telController;
  // 密码输入框控制器
  TextEditingController pswController;
  // 手机输入框控制器(验证码登录)
  TextEditingController iptPhoneController;
  // tabbar控制器
  TabController tabBarController;
  // tabar选项
  List<String> tabTitles = [
    "密码登录",
    "验证码登录",
  ];
  // 登录中加载状态
  bool loginlock = false;

// life-------------------------------------------------------------------------

  @override
  void initState() {
    super.initState();
    tabBarController = TabController(length: tabTitles.length, vsync: this);
    telController = TextEditingController();
    pswController = TextEditingController();
    iptPhoneController = TextEditingController();
  }

  @override
  void dispose() {
    super.dispose();
    tabBarController.dispose();
  }

// methods----------------------------------------------------------------------

  // 登录方法
  _loginAction() async {
    if (!canLogin) return;
    canLogin = false;
    String tel = telController.text;
    String psw = pswController.text;
    var result = await UserApis.login(tel, psw);
    canLogin = true;
    if (result != null && result['status'] == 1) {
      setState(() {
        loginlock = true;
      });
      CommonAction.initAppData(context, result['msg']).then((val) {
        showToast("登录成功");
        goPage(context, "/", clearStack: true);
      });
    }
  }

  // 验证码登录
  void _getPIN() async {
    String phone = iptPhoneController.text;
    var result = await UserApis.getPIN(phone, context);
    if (result != null && result['status'] == 1) {
      print(result);
      goPage(context, "/inputCode", param: {'phone': phone});
    }
  }

// widget-----------------------------------------------------------------------

  /// 登录按钮文字
  Widget _loginBtnStutas() {
    if (loginlock) {
      return CupertinoActivityIndicator();
    } else {
      return Text(
        "登录",
        style: TextStyle(
          color: col('6f53ff'),
          fontSize: px(36),
        ),
      );
    }
  }

  /// 背景图
  Widget bg() {
    return Container(
      width: w100(context),
      height: h100(context),
      child: Image.asset(
        'assets/images/homeBg1.png',
        fit: BoxFit.cover,
      ),
    );
  }

  /// 返回
  Widget back() {
    return Container(
      margin: EdgeInsets.only(top: px(35)),
      width: px(150),
      height: px(150),
      // child: IconButton(
      //     onPressed: _back,
      //     icon: Container(
      //       alignment: Alignment.topLeft,
      //       margin: EdgeInsets.only(left: px(40)),
      //       child: Icon(
      //         Icons.arrow_back_ios,
      //         color: Colors.white,
      //         size: px(36),
      //       ),
      //     )),
    );
  }

  /// logo
  Widget logo() {
    return Container(
      width: w100(context),
//      margin: EdgeInsets.only(top: px(250)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          /// logo
          Container(
            width: px(154),
            height: px(154),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: Image.asset('assets/images/icon/logo.jpg'),
            ),
          ),

          /// logoText
          // Container(
          //   width: px(318),
          //   margin: EdgeInsets.only(top: px(52)),
          //   child: Image.asset('assets/images/icon/logoText.png'),
          // ),
        ],
      ),
    );
  }

  // AppBar
  Widget _appBar() {
    return Container(
      height: px(490),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/images/loginbg.jpg"),
          fit: BoxFit.cover,
        ),
      ),
      child: Stack(
        children: <Widget>[
          Container(
            width: w100(context),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset(
                  "assets/images/icon/logo.jpg",
                  width: px(154),
                  height: px(154),
                ),
                Container(
                  margin: EdgeInsets.only(top: px(50)),
                  child: Text(
                    "欢迎来到趣果直播",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: px(38),
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 生成body
  Widget _bodyHandle() {
    return ListView(
      padding: EdgeInsets.all(0),
      children: <Widget>[
        // 头部logo
        _appBar(),
        // tabbar选择器
        _tabBar(),
        // tabbarview选择器视图
        _tabBarView(),
      ],
    );
  }

  // 头部tabbar
  Widget _tabBar() {
    return Container(
      margin: EdgeInsets.only(top: px(120)),
      padding: EdgeInsets.symmetric(horizontal: px(40)),
      child: TabBar(
        isScrollable: true,
        controller: tabBarController,
        labelColor: col("ffffff"),
        labelPadding: EdgeInsets.symmetric(horizontal: px(20)),
        labelStyle: TextStyle(
          fontSize: px(46),
          fontWeight: FontWeight.bold,
        ),
        unselectedLabelStyle: TextStyle(fontSize: px(30)),
        unselectedLabelColor: col("ecdbf1"),
        indicator: BoxDecoration(),
        tabs: tabTitles.map<Tab>((item) {
          return Tab(text: item);
        }).toList(),
      ),
    );
  }

  // tabbarview视图
  Widget _tabBarView() {
    return Container(
      height: px(1000),
      child: TabBarView(
        controller: tabBarController,
        children: [
          _pswLogin(),
          _codeLogin(),
        ],
      ),
    );
  }

  // 密码登录
  Widget _pswLogin() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: px(60)),
      child: Column(
        children: <Widget>[
          /// 手机输入框
          Container(
            margin: EdgeInsets.only(top: px(30)),
            child: TextField(
              controller: telController,
              inputFormatters: [
                WhitelistingTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(11),
              ],
              textInputAction: TextInputAction.next,
              keyboardType: TextInputType.phone,
              style: TextStyle(color: col("ffffff")),
              decoration: InputDecoration(
                labelText: "手机号码",
                labelStyle: TextStyle(color: col("deb2de")),
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: col('d1a3d7')),
                ),
                focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.cyan),
                ),
              ),
            ),
          ),

          /// 密码输入框
          Container(
            margin: EdgeInsets.only(top: px(50)),
            child: TextField(
              controller: pswController,
              obscureText: true,
              textInputAction: TextInputAction.next,
              style: TextStyle(color: col("ffffff")),
              decoration: InputDecoration(
                labelText: "密码",
                labelStyle: TextStyle(color: col("deb2de")),
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: col('d1a3d7')),
                ),
                focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.cyan),
                ),
              ),
            ),
          ),

          /// 登录按钮
          Container(
            width: px(630),
            height: px(94),
            margin: EdgeInsets.only(top: px(90)),
            child: RaisedButton(
              onPressed: canLogin ? _loginAction : null,
              color: col("ffffff"),
              disabledColor: col("c5baff"),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(
                  sp(47),
                ),
              ),
              child: _loginBtnStutas(),
            ),
          ),

          /// 忘记密码和注册账号
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Container(
                  height: px(66),
                  margin: EdgeInsets.only(top: px(20)),
                  child: FlatButton(
                    onPressed: () {},
                    padding: EdgeInsets.symmetric(horizontal: px(25)),
                    child: Text(
                      "忘记密码",
                      style: TextStyle(
                        color: col("f4e6ee"),
                        fontSize: px(28),
                      ),
                    ),
                  ),
                ),
                Container(
                  height: px(66),
                  margin: EdgeInsets.only(top: px(20)),
                  child: FlatButton(
                    onPressed: () => goPage(context, "/register"),
                    padding: EdgeInsets.symmetric(horizontal: px(25)),
                    child: Text(
                      "注册账号",
                      style: TextStyle(
                        color: col("f4e6ee"),
                        fontSize: px(28),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),

          /// 服务协议
          _agreement(),
        ],
      ),
    );
  }

  // 验证码登录
  Widget _codeLogin() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: px(60)),
      child: Column(
        children: <Widget>[
          /// 手机输入框
          Container(
            margin: EdgeInsets.only(top: px(30)),
            child: TextField(
              controller: iptPhoneController,
              inputFormatters: [
                WhitelistingTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(11),
              ],
              keyboardType: TextInputType.phone,
              style: TextStyle(color: col("ffffff")),
              decoration: InputDecoration(
                labelText: "手机号码",
                labelStyle: TextStyle(color: col("deb2de")),
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: col('d1a3d7')),
                ),
                focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.cyan),
                ),
              ),
            ),
          ),

          /// 登录按钮
          Container(
            width: px(630),
            height: px(94),
            margin: EdgeInsets.only(top: px(90)),
            child: RaisedButton(
              onPressed: _getPIN,
              color: col("ffffff"),
              disabledColor: col("c5baff"),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(
                  sp(47),
                ),
              ),
              child: Text(
                "获取验证码",
                style: TextStyle(
                  color: col('6f53ff'),
                  fontSize: px(36),
                ),
              ),
            ),
          ),
          // 注册账号
          // Container(
          //   child: Row(
          //     mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          //     children: <Widget>[
          //       Container(
          //         height: px(66),
          //         margin: EdgeInsets.only(top: px(20)),
          //         child: FlatButton(
          //           onPressed: () {
          //             goPage(context, "/register");
          //           },
          //           padding: EdgeInsets.symmetric(horizontal: px(25)),
          //           child: Text(
          //             "注册账号",
          //             style: TextStyle(
          //               color: col("ffffff"),
          //               fontSize: px(28),
          //             ),
          //           ),
          //         ),
          //       ),
          //     ],
          //   ),
          // ),
          // 服务协议
          _agreement(),
        ],
      ),
    );
  }

  // 更多的登录方式
  Widget _moreLogin() {
    return Container(
      margin: EdgeInsets.only(top: px(120)),
      padding: EdgeInsets.symmetric(horizontal: px(60)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          _moreLoginBtn("assets/images/icon/wechat.png", () => {}),
          _moreLoginBtn("assets/images/icon/qq.png", () => {}),
        ],
      ),
    );
  }

  // 更多登录方式按钮构造函数
  _moreLoginBtn(iconUrl, loginAction) {
    return Container(
      width: px(80),
      height: px(80),
      child: FlatButton(
        onPressed: loginAction,
        color: col("edeff2"),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(
            sp(40),
          ),
        ),
        padding: EdgeInsets.all(0),
        child: Image.asset(
          iconUrl,
          width: px(50),
          height: px(42),
        ),
      ),
    );
  }

  // 服务协议
  Widget _agreement() {
    return Container(
      margin: EdgeInsets.only(top: px(60)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            "确认登录即代表已阅读并同意",
            style: TextStyle(
              fontSize: px(22),
              color: col("ffffff"),
            ),
          ),
          IconButton(
            onPressed: () async {
              // showCupertinoDialog(
              //   context: context,
              //   builder: (ctx) {
              //     return CupertinoAlertDialog(
              //       title: Text('用户协议与隐私条款'),
              //       content: Text('是否已阅读并同意我们对条款'),
              //       actions: <Widget>[
              //         CupertinoDialogAction(
              //           onPressed: () => Navigator.pop(ctx, false),
              //           child: Text('取消'),
              //         ),
              //         CupertinoDialogAction(
              //           onPressed: () => Navigator.pop(ctx, true),
              //           child: Text('确定'),
              //         ),
              //       ],
              //     );
              //   },
              // );
              String link = "http://www.tangzhijiaowh.cn/privacy.html";
              if (await canLaunch(link)) {
                await launch(link);
              }
            },
            padding: EdgeInsets.zero,
            iconSize: px(150),
            icon: Text(
              "《隐私协议》",
              style: TextStyle(
                fontSize: px(22),
                color: col("ffffff"),
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          IconButton(
            onPressed: () async {
              String link = "http://www.tangzhijiaowh.cn/user.html";
              if (await canLaunch(link)) {
                await launch(link);
              }
            },
            padding: EdgeInsets.zero,
            iconSize: px(150),
            icon: Text(
              "《用户政策》",
              style: TextStyle(
                fontSize: px(22),
                color: col("ffffff"),
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          bg(),

          /// 内容
          SingleChildScrollView(
            child: SafeArea(
              child: Container(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    /// 返回
                    back(),

                    /// logo
                    logo(),

                    Container(
                      padding: EdgeInsets.only(
                        left: px(60),
                        right: px(60),
                        top: px(150),
                      ),
                      child: Text(
                        '验证码登录',
                        style: TextStyle(
                          fontSize: px(46),
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),
                    ),

                    _codeLogin(),

                    /// tabBar
                    // _tabBar(),

                    // /// tabBarView
                    // _tabBarView(),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
